<template>
	<view class="exam">
		<!-- 考试界面 type  a"选择题" b"判断题" c"填空题" d"简答题" -->
		<view class="title" style="text-align: center;">HTMLCSS 试卷</view>
		<view class="exam-box">
			<view class="left" @click="examStartFn">
				<text style="color: #333333;" v-if="status==1">开始考试</text>
				<text style="color: #4393F4;" v-if="status==2">考试中..</text>
				<text style="color: #ff0000;" v-if="status==3">考试结束</text>
			</view>
			<view class="left"><text style="color: #4393F4;">{{time2}}</text></view>
		</view>
		<view class="exam-main">
			<swiper>
				<swiper-item v-for="(item,index) in arr" :key="index">
					<view class="swiper-item">
						<!-- 选择题 -->
						<view class="box" v-if="item.type == 'a'">
							<view class="tit">选择题</view>
							<view class="q">{{index + 1}}.{{item.question}}</view>
							<view class="option">
								<view v-for="(opt, count) in item.options" :key="opt.id"
									:class="['text',opt.checked ?'active':'']"
									@click="chooseAnswerFn(index, count, opt.text)">
									{{opt.text}}
								</view>
							</view>
						</view>
						<!-- 判断题 -->
						<view class="box" v-if="item.type == 'b'">
							<view class="tit">判断题</view>
							<view class="q">{{index + 1}}.{{item.question}}</view>
							<view class="option">
								<view v-for="(opt,count) in item.options" :key="opt.id"
									:class="['text',opt.checked ?'active':'']"
									@click="chooseAnswerFn(index, count, opt.text)">
									{{opt.text}}
								</view>
							</view>
						</view>
						<!-- 填空题 -->
						<view class="box" v-if="item.type == 'c'">
							<view class="tit">填空题</view>
							<view class="q">{{index + 1}}.{{item.question}}</view>
							<view class="inpbox">
								<input v-model="item.myAnswer" class="inp" type="text" placeholder="请输入" />
							</view>
						</view>
						<!-- 简单题 -->
						<view class="box" v-if="item.type == 'd'">
							<view class="tit">简答题</view>
							<view class="q">{{index + 1}}.{{item.question}}</view>
							<view class="inpbox">
								<textarea v-model="item.myAnswer" class="textarea" placeholder="请输入你的理解" id="" cols="30"
									rows="10"></textarea>
							</view>
						</view>
					</view>
				</swiper-item>
			</swiper>
		</view>
		<view class="exam-footer">
			<view class="label"></view>
			<view class="label" @click="showMaskFn"><text>答题卡</text></view>
			<view class="label"></view>
		</view>
		<view class="mask" v-if="isShow">
			<view class="title">答题序号</view>
			<!-- 所有题 -->
			<view class="point-box">
				<view v-for="(item,index) in arr" :key="item.id"
					:class="['point',(item.done || item.myAnswer != '')?'active':'']">{{index + 1}}
				</view>
			</view>
			<view class="mask-footer">
				<view class="btn" @click="closeMaskFn">继续答题</view>
				<view class="btn btn-success" @click="confirmFn">提交试卷</view>
			</view>
		</view>
	</view>
</template>

<script>
	// 创建db对象
	const db = uniCloud.database();
	// 获取 `tt_scores` 集合的引用
	const scoresCollection = db.collection('tt_scores');

	export default {
		data() {
			return {
				isShow: false,
				time2: '00:00:00',
				seconds: 0,
				status: 1, // 设置 “考试考试” “考试中” “考试结束”
				examInfo: {
					user: "",
					account: "",
				},
				arr: [],
				isStart: false,
				time: 0,
				// 倒计时函数
				t: null,
				isTip: true
			}
		},
		methods: {
			closeMaskFn() {
				this.isShow = false
			},
			showMaskFn() {
				this.isShow = true
			},
			// 点击开始考试
			examStartFn() {
				// console.log('test')
				this.isStart = true;
				this.status = 2
				this.downTimeFn(); // 考试倒计时
			},
			downTimeFn() {
				if (this.t != null) {
					clearInterval(this.t);
				}
				this.time2 = this.formatime(this.seconds)
				this.t = setInterval(() => {
					this.seconds--;
					if (this.seconds <= 30 && this.isTip) {
						this.isTip = false;
						uni.showToast({
							title: "还有30s结束考试",
							icon: "none"
						})
						uni.showToast({
							title: "抓紧提交试卷",
							icon: "none"
						})
					}
					if (this.seconds < 0) {
						clearInterval(this.t);
						this.isStart = false;
						this.status = 3;
						uni.showToast({
							title: "考试结束",
							icon: "none"
						})
						return false;
					}
					this.time2 = this.formatime(this.seconds)
				}, 1000)
			},
			formatime() {
				let h = 0,
					m = 0,
					s = 0;
				h = Math.floor((this.seconds / 3600))
				m = Math.floor((this.seconds % 3600) / 60)
				s = Math.floor((this.seconds % 60))
				h = h < 10 ? '0' + h : h;
				m = m < 10 ? '0' + m : m;
				s = s < 10 ? '0' + s : s;

				return `${h}:${m}:${s}`
			},
			// 编写方法选择答案
			// i 第几道题目
			// j 第几个选项
			chooseAnswerFn(i, j, text) {
				if (!this.isStart) {
					uni.showToast({
						title: "尚未开始考试",
						icon: "none"
					})
					return false;
				}
				if (this.arr[i] && this.arr[i].type == 'a') {
					this.arr[i].done = true; // 判断用户是否选择了答案， 答题卡做标签背景高亮的开关
					this.arr[i].options.forEach(opt => {
						opt.checked = false
					})
					this.arr[i].options[j].checked = true;
					// 添加属性：用户选择的答案
					let v1 = text.slice(0, 1)
					this.arr[i].myAnswer = v1;
					// console.log(arr.value);
				}

				if (this.arr[i] && this.arr[i].type == 'b') {
					this.arr[i].done = true; // 判断用户是否选择了答案， 答题卡做标签背景高亮的开关
					this.arr[i].options.forEach(opt => {
						opt.checked = false
					})
					this.arr[i].options[j].checked = true;
					// 添加属性：用户选择的答案
					let v1 = text.slice(0, 1)
					this.arr[i].myAnswer = v1;
					// console.log(arr.value);
				}

			},
			// 编写函数获取试卷信息
			async getExamDetailFn(_id) {
				uni.showLoading({
					title: "加载题目中..."
				})
				let that = this;
				await uniCloud.callFunction({
						name: 'exam',
						data: {
							_id: _id
						}
					})
					.then(
						resData => {
							console.log(resData)
							if (resData.result && resData.result.data) {

								if (resData.result.data && resData.result.data[0].topics) {

									let topics = resData.result.data[0].topics
									let arr2 = topics.map(item => {
										item.myAnswer = "";
										return item;
									})
									// 试卷的题目
									that.arr = arr2;
									that.time = resData.result.data[0].time //时长
									that.seconds = resData.result.data[0].time * 60 * 60 // 总秒数
									// 记录试卷信息
									let obj3 = resData.result.data[0];
									that.examInfo = {
										// _id: xxx
										paper: obj3.paper,
										name: obj3.name,
										text: obj3.text,
										id: obj3.id,
										src: obj3.src,
										info: obj3.info,
										total: obj3.total,
										passline: obj3.passline,
										time: obj3.time,
										account: obj3.account,
									};
								}
							}

						}
					)
					.catch(err => {
						console.log(err)
						uni.hideLoading();
					})

				uni.hideLoading();
			},
			// 提交试卷
			async jumpToResultFn() {
				// console.log(this.arr)
				let allTopics = this.arr;
				let score = 0;
				allTopics.forEach((item, index) => {
					if (item.myAnswer == item.answer) {
						score += (item.value - 0)
					}
				})
				// console.log("用户的得分:", score);
				let info = uni.getStorageSync("INFO")
				let account = info.account;
				let user = info.user;
				console.log({
					account,
					user
				});
				this.examInfo.score = score;
				this.examInfo.topics = allTopics;
				this.examInfo.user = user;
				this.examInfo.account = account;
				const date2 = new Date();
				const createAt = date2.getTime();
				this.examInfo.createAt = createAt;
				this.examInfo.isPass = score >= this.examInfo.passline ? '及格' : "不及格"
				console.log("用户的得分:", this.examInfo);
				uni.showLoading({
					title: "正在统计分数"
				})
				await scoresCollection.add(this.examInfo)
					.then(
						resData => {
							console.log("成绩ID:", resData)
							if (resData.result && resData.result.id) {
								setTimeout(() => {
									// redirectTo  没有上一级历史记录
									uni.redirectTo({
										url: `/pages/result/result?id=${resData.result.id}`
									})
								}, 500)
							} else {
								uni.showToast({
									title: "统计分数失败",
									icon: "none"
								})
							}

						}
					)
					.catch(err => {
						console.log(err)
						uni.hideLoading()
					})
				uni.hideLoading()

			},
			confirmFn() {
				console.log("test", this.isStart)
				let that = this;
				if (!this.isStart) {
					uni.showToast({
						title: "尚未开始考试",
						icon: "none",
						mask: true
					})
					return false;
				}
				if (this.status == 3) {
					uni.showToast({
						title: "考试结束了",
						icon: "none",
						mask: true
					})
					return false;
				}
				uni.showModal({
					title: '温馨提示',
					content: "您要提交试卷了吗",
					success() {
						that.jumpToResultFn();
					}
				})
			}
		},
		onLoad(options) {
			// 接收URL中的参数
			if (options._id) {
				let _id = options._id;
				this.getExamDetailFn(_id)
			}
		}
	}
</script>



<style lang="scss">
	@import "../../static/scss/variable.scss";

	.exam {
		padding: $padd;



		swiper {
			height: 800rpx;
			background-color: #f0f0f0;
			overflow: scroll;

			.box {
				padding: 20rpx;

				.tit {
					margin-bottom: 20rpx;
				}

				.q {
					font-weight: bold;
					font-size: 32rpx;
				}

				.text {
					padding: 10rpx 30rpx;
					margin-bottom: 10rpx;
					margin-top: 10rpx;

					&.active {
						background-color: $theme-color;
						color: #fff;
					}
				}

				.inpbox {
					margin-bottom: 10rpx;
					margin-top: 20rpx;

					.inp {
						background-color: #fff;
						border-bottom: 1px solid #ccc;
						height: 90rpx;
						padding: 0rpx 20rpx;
						box-sizing: border-box;
						width: 100%;
					}

					.textarea {
						background-color: #fff;
						width: 100%;
						box-sizing: border-box;
						padding: 20rpx;
						border-radius: 10rpx;
					}
				}
			}
		}
	}

	::-webkit-scrollbar {
		display: none;
	}

	.mask {
		position: fixed;
		top: 0;
		left: 0;
		z-index: 10;
		width: 100%;
		height: 100%;
		background-color: rgba(255, 255, 255, .95);
		padding: 20rpx 30rpx;
		box-sizing: border-box;
		padding-bottom: 150rpx;
		box-sizing: border-box;
		overflow: scroll;

		.point-box {
			width: 100%;
			display: flex;
			flex-wrap: wrap;
			justify-content: flex-start;
			padding: 30rpx 0rpx;

			.point {
				margin: 10rpx;
				width: 80rpx;
				height: 80rpx;
				border: 1px solid #ccc;
				text-align: center;
				line-height: 80rpx;
				color: #666;

				// border-radius: 50%;
				&.active {
					background-color: $theme-color;
					color: #fff;
				}
			}
		}

		.mask-footer {
			width: 100%;
			height: 150rpx;
			position: fixed;
			bottom: 0;
			left: 0;
			z-index: 11;
			display: flex;
			justify-content: center;
			align-items: center;

			.btn {
				margin: 10px;
				border: 1px solid #ccc;
				height: 70rpx;
				line-height: 70rpx;
				padding: 0rpx 20rpx;
				border-radius: 10rpx;
			}

			.btn-success {
				color: #1BA035;
				border: 1px solid #1BA035;
			}
		}
	}

	.exam-footer {
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 5;
		width: 100%;
		display: flex;
		justify-content: space-between;
		height: 120rpx;
		align-items: center;
		background-color: #f0f0f0;
	}

	.exam-box {
		width: 100%;
		padding: 20rpx 10rpx;
		box-sizing: border-box;
		display: flex;
		justify-content: space-between;
	}
</style>